package rad.framework.mda.jpagen.actions;

import rad.framework.mda.generator.Console;
import rad.framework.mda.util.ModelUtil;

import org.eclipse.emf.common.util.EList;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.uml2.uml.Class;
import org.eclipse.uml2.uml.NamedElement;
import org.eclipse.uml2.uml.Property;
import org.eclipse.uml2.uml.Stereotype;

/**
 * @author boudyacho
 * 
 */
public class AddEmbeddedActionExtension extends BaseUtiltiyActionExtension {

	protected static final String EMBEDDED = "javax.persistence.Embedded";

	protected static final String EMBEDDABLE = "javax.persistence.Embeddable";

	public void fillContextMenu(IMenuManager aMenu) {
		getSubMenu(aMenu).add(new AddEmbeddedAction());
	}

	protected void execute(Class clazz) {
		EList<NamedElement> list = clazz.getMembers();
		for (NamedElement namedElement : list) {
			if (namedElement instanceof Property) {
				execute((Property) namedElement);
			}
		}
	}

	protected void execute(Property property) {
		if (ModelUtil.isStereotypeApplied(property.getType(), EMBEDDABLE)
				&& !ModelUtil.isStereotypeApplied(property, EMBEDDED)) {
			setEmbedded(property);
			Console.getStream().println(
					"Added " + EMBEDDED + " stereotype - "
							+ property.getQualifiedName());
		}
	}

	protected void setEmbedded(NamedElement element) {
		Stereotype stereotype = (Stereotype) ModelUtil.getProfileElement(
				element, EMBEDDED);
		if (stereotype != null) {
			element.applyStereotype(stereotype);
		}
	}

	private class AddEmbeddedAction extends BaseUtilityAction {
		private static final String LABEL = "Add Embedded Stereotypes";

		public AddEmbeddedAction() {
			super(LABEL);
		}
	}
}
